package org.budo.asr.service.huawei;

import org.budo.asr.service.api.AsrRequest;
import org.budo.asr.service.api.AsrResponse;
import org.budo.asr.service.api.DefaultAsrResponse;
import org.budo.support.lang.util.ThreadUtil;

import com.huawei.sis.bean.request.AsrCustomLongRequest;
import com.huawei.sis.bean.response.AsrCustomLongResponse;
import com.huawei.sis.client.AsrCustomizationClient;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * 定制语音识别 demo、包含录音文件识别
 */
@Slf4j
@Getter
@Setter
public class HuaweiAsrService extends AbstractHuaweiAsrService {
    // 录音文件识别参数
    private String obsAudioFormat = ""; // 文件格式，如auto等

    private String obsProperty = ""; // 属性字符串，如chinese_8k_common等

    @Override
    public AsrResponse recognition(AsrRequest req) {
        AsrCustomizationClient asrCustomizationClient = this.asrCustomizationClient();

        // 2. 生成请求
        AsrCustomLongRequest request = new AsrCustomLongRequest(req.getUrl(), this.getObsAudioFormat(), this.getObsProperty());

        // 设置请求参数，所有参数均为可选
        this.setLongParameter(request);

        String jobId = this.submitJob(asrCustomizationClient, request);

        Integer retry = null == req.getRetry() ? this.getRetry() : req.getRetry();
        Integer period = null == req.getPeriod() ? this.getPeriod() : req.getPeriod();

        // 4 轮询jobId，获取最终结果。
        int count = 0;
        int success = 0;

        AsrCustomLongResponse response = null;
        while (count < retry) {
            log.info("#109 正在进行第" + count + "次尝试");
            response = this.getAsrLongResponse(asrCustomizationClient, jobId);
            String status = response.getStatus();

            // 成功
            if (status.equals("FINISHED")) {
                success = 1;
                break;
            }

            // 失败
            if (status.equals("ERROR")) {
                log.info("#116 执行失败, 无法根据jobId获取结果");
                return null;
            }

            // 继续
            ThreadUtil.sleep(period);
            count++;
        }

        // 打印结果
        if (success == 0) {
            log.info("#129 已进行" + count + "次尝试，无法获取识别结果。 jobId为 " + jobId);
            return null;
        }

        String responseBody = this.obj2Str(response);
        return new DefaultAsrResponse().setResponseBody(responseBody);
    }
}
